package com.example.administrator.waitan.find.life.LifeContentActivity;

import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.administrator.waitan.R;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2016/1/20.
 */
public class DownLoadContentService extends Service {
    private DownLoadContentBinder downLoadContentBinder = new DownLoadContentBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return downLoadContentBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class DownLoadContentBinder extends Binder {
        Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case 2:
                        Intent sendMessageIntent = new Intent();
                        sendMessageIntent.setAction("DOWNLOAD_LIFECONTENT");
                        sendBroadcast(sendMessageIntent);
                        Toast.makeText(getApplicationContext(), "已发送广播", Toast.LENGTH_SHORT).show();
                        break;
                }
                stopSelf();
                return false;
            }

        });

        public void DownLoadContent(final String url, final ImageView imageView) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final RequestQueue queue;
                    queue = Volley.newRequestQueue(getApplication());
                    StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView, R.mipmap.mi_icon, R.mipmap.mi_icon);
                            ImageLoader imageLoader = new ImageLoader(queue, new DoubleCache());
                            imageLoader.get(url, listener);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
                    queue.add(request);
                    handler.sendEmptyMessage(2);
                }
            }).start();
        }
    }

    class MemoryCache implements ImageLoader.ImageCache {
        private LruCache<String, Bitmap> lruCache;//创建内存对象

        public MemoryCache() {
            long maxMemory = Runtime.getRuntime().maxMemory();//得到运行时最大内存
            int cacheSize = (int) (maxMemory / 4);
            lruCache = new LruCache<String, Bitmap>(cacheSize) {

                @Override
                protected int sizeOf(String key, Bitmap value) {
                    return value.getRowBytes() * value.getHeight() / 1024;
                }
            };//构建内存对象 并设置内存大小

        }

        @Override
        public Bitmap getBitmap(String url) {
            return lruCache.get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            lruCache.put(url, bitmap);
        }
    }

    //创建文件缓存对象
    class DiskCache implements ImageLoader.ImageCache {//存放图片的方法
        private String cacheDir = "";//定义文件储存路径

        public DiskCache() {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File root = Environment.getExternalStorageDirectory();
                File cacheFilr = new File(root.getAbsolutePath() + "/waiTan");
                if (!cacheFilr.exists()) {//判断cacheFilr是否存在
                    cacheFilr.mkdir();//创建此文件
                }
                //如果文件夹存在,这获取路径
                cacheDir = cacheFilr.getAbsolutePath();
            }
        }

        @Override
        public Bitmap getBitmap(String url) {
            //截取到url最后一个点的后四位  为文件名字
            url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
//            url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
            return BitmapFactory.decodeFile(cacheDir + "/" + url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {//读取图片的方法
            url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
            FileOutputStream fileOutputStream = null;
            try {
                //读取文件流的url
                fileOutputStream = new FileOutputStream(cacheDir + "/" + url);
                //将图片显示到组件上   jpeg为显示格式  100为质量
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (null != fileOutputStream) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    //控制两个缓存类的类
    class DoubleCache implements ImageLoader.ImageCache {
        private MemoryCache memoryCache;
        private DiskCache diskCache;

        public DoubleCache() {
            memoryCache = new MemoryCache();
            diskCache = new DiskCache();
        }

        @Override
        public Bitmap getBitmap(String url) {
            Bitmap bitmap = memoryCache.getBitmap(url);
            if (null == bitmap) {
                bitmap = diskCache.getBitmap(url);
            }
            return bitmap;
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            memoryCache.putBitmap(url, bitmap);//存入内存缓存一份
            diskCache.putBitmap(url, bitmap);//存入硬盘缓存一份
        }
    }


    class DownloadImage extends AsyncTask<String, Void, InputStream> {

        @Override
        protected InputStream doInBackground(String... strings) {
            return null;
        }
    }
}
